vil = readShapePoly("./data/maps/admin_maps/gadm36_IDN_shp/gadm36_IDN_4.shp")
vil@data$id = rownames(vil@data)
vil@data$prov_id = substring(vil@data$CC_4, first = 1, last = 2)
vil = vil[!is.na(vil@data$prov_id),]
vil = vil[vil@data$prov_id > 30 & vil@data$prov_id < 40,]


op = readShapePoly("./data/maps/opium_maps/opium_banned_1886.shp")
boundary = readShapeLines("./data/maps/opium_maps/opium_boundary_1886.shp") 

#intersection
#clip = gIntersection(op, vil, byid = TRUE, drop_lower_td = TRUE) #clip polygon 2 with polygon 1
#clip.points = fortify(clip)

#calculate kecamatan distance to boundary
df <- matrix(NA, ncol = 5, nrow = 30000)

for(i in 1:length(vil@polygons)){
  df[i,] <- c(i,
              as.character(dist2Line(vil@polygons[[i]]@Polygons[[1]]@labpt, boundary)[1,1]), 
              as.character(vil@polygons[[i]]@Polygons[[1]]@labpt),
              as.character(vil@polygons[[i]]@ID))
}



distances =
  df %>%
  data.frame() %>%
  set_colnames(c("rowid", "distance", "long", "lat", "id")) %>%
  dplyr::select(-rowid) %>%
  na.omit() %>%
  mutate_at(vars("lat", "long", "distance"), funs(as.numeric(as.character(.)))) %>%
  left_join(.,
            data.frame(
              id = vil@data$id,
              vil_code = vil@data$CC_4),
            by = "id")


spcoord = 
  distances %>%
  dplyr::select("lat", "long")

coordinates(spcoord) = ~long + lat

#finding communities in banned area
banned =
  over(spcoord, op) %>%
  mutate(rowid = rownames(.),
         rowid = as.numeric(rowid)) %>%
  mutate(id = case_when(is.na(id) ~ 0,
                        TRUE ~ 1)) %>%
  set_colnames(c("opium_ban", "rowid"))

vil_distances = 
  distances %>%
  rowid_to_column() %>%
  left_join(., banned, by = "rowid") %>%
  mutate(opium_legal = case_when(opium_ban == 0 ~ 1,
                                 opium_ban == 1 ~ 0,
                                 TRUE ~ NA_real_),
         forcing = case_when(opium_legal == 0 ~ (distance - (distance*2)),
                             opium_legal == 1 ~ distance,
                             TRUE ~ NA_real_)) %>%
  dplyr::select(-opium_ban)


write.csv(vil_distances, "./data/maps/distances_csvs/village_distance.csv")
